using System;
using System.Security;
using System.Runtime.InteropServices;

namespace GeoFramework.IO.Bluetooth
{
	/// <summary>
	/// This structure is derived from a binary large object (BLOB) and contains information about a block of data.
	/// </summary>
#if !PocketPC
    [SuppressUnmanagedCodeSecurity()]
#endif
	internal class BLOB : IDisposable
	{
		private byte[] m_data;

		private GCHandle m_blobhandle;
		private BTHNS_BLOB m_blob;

		public BLOB(BTHNS_BLOB blob)
		{
			m_data = new byte[8];

			m_blob = blob;
			m_blobhandle = GCHandle.Alloc(blob.ToByteArray(), GCHandleType.Pinned);
			
			//write to the byte array
			BitConverter.GetBytes(m_blob.Length).CopyTo(m_data, 0);
			int memloc = 0;
#if !Framework10
			if((System.Environment.OSVersion.Platform == PlatformID.WinCE) && (System.Environment.Version.Major == 1))
			{
				memloc = m_blobhandle.AddrOfPinnedObject().ToInt32() + 4;
			}
			else
			{
#endif
				memloc = m_blobhandle.AddrOfPinnedObject().ToInt32();
#if !Framework10
			}
#endif
			BitConverter.GetBytes(memloc).CopyTo(m_data, 4);
		}

        //public int Size
        //{
        //    get
        //    {
        //        return BitConverter.ToInt32(m_data, 0);
        //    }
        //}

        //public BTHNS_BLOB BlobData
        //{
        //    get
        //    {
        //        return m_blob;
        //    }
        //}

		public byte[] ToByteArray()
		{
			return m_data;
		}

		#region IDisposable Members

		protected void Dispose(bool disposing)
		{
            GC.SuppressFinalize(this);

			if(m_blobhandle.IsAllocated)
			{
				m_blobhandle.Free();
			}

			if(disposing)
			{
				m_blob = null;
				m_data = null;
			}
		}

		public void Dispose()
		{
			Dispose(true);
		}

		~BLOB()
		{
			//System.Windows.Forms.MessageBox.Show("Disposing Bluetooth BLOB");
			Dispose(false);
		}

		#endregion
	}
}
